﻿using System;
using System.Collections.Generic;
using Local.Service;
using NReader.Model;
using NReader.Model.RAS;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using XnReader.WinRT.Controlx;

// “分组项页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234231 上提供

namespace XnReader.WinRT.Forms
{
    /// <summary>
    /// 显示分组的项集合的页。
    /// </summary>
    public sealed partial class Bookcase : XnReader.WinRT.Common.LayoutAwarePage
    {
        /// <summary>
        /// 默认显示的第一个书架编号
        /// </summary>
        private int _bookcaseId = 1;

        public Bookcase()
        {
            InitializeComponent();
            var visiblesHeader = new CommandInfo
                                     {
                                         Theme = "black",
                                         VisibleLogo = Visibility.Visible,
                                         VisibleOnlineStore = Visibility.Visible,
                                         VisibleImport = Visibility.Visible
                                     };
            if (header != null)
            {
                header.DataContext = visiblesHeader;
                header.ImportClickEvent += ImportClickEvent;
            }
            var visiblesFooter = new CommandInfo
                                     {
                                         Theme = "white",
                                         VisibleAbout = Visibility.Visible,
                                         VisibleModify = Visibility.Visible,
                                         VisibleRating = Visibility.Visible,
                                         VisibleUpdate = Visibility.Visible
                                     };
            if (footer != null)
            {
                footer.DataContext = visiblesFooter;
                footer.ModifyClickEvent += FooterModifyClickEvent;
            }
        }

        /// <summary>
        /// 跳转到书架编辑页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void FooterModifyClickEvent(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(BookcaseModify), _bookcaseId);
        }

        /// <summary>
        /// 缓存当前选中的文件
        /// </summary>
        private IReadOnlyList<StorageFile> _pickerFiles; 

        /// <summary>
        /// 导入本地文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ImportClickEvent(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker
                             {SuggestedStartLocation = PickerLocationId.PicturesLibrary, ViewMode = PickerViewMode.List};
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeFilter.Add(".txt");
            _pickerFiles = await picker.PickMultipleFilesAsync();
            if (_pickerFiles.Count > 0)
            {
                string files = string.Empty;
                foreach (StorageFile file in _pickerFiles)
                {
                    files += file.Name + "\r\n";
                }
                txtFiles.Text = files;
                tbTips.Text = string.Format("您选择导入的书籍(共 {0} 本)", _pickerFiles.Count.ToString());
                if (!popBookcases.IsOpen)
                {
                    borderPopBookcases.Visibility = Visibility.Visible;
                    popBookcases.IsOpen = true;
                }
            }
        }

        private async void ConfirmpopBookcasesClicked(object sender, RoutedEventArgs e)
        {
            if (popBookcases.IsOpen)
            {
                if (_pickerFiles != null && _pickerFiles.Count > 0)
                {
                    await Utils.CheckFolder("document");
                    var folder = ApplicationData.Current.LocalFolder;
                    var subfolder = await folder.GetFolderAsync("document");
                    var maxid =await NReader.Service.ArticleService.Instance().GetArticleMaxID();

                    var bookcase = cmbBookcases.SelectedItem as BookcaseInfo;
                    var bookcaseid = 1;//默认书架ID
                    if (bookcase != null) bookcaseid = bookcase.id;
                   
                    //验证数量
                    var count =await NReader.Service.ArticleService.Instance().GetBookStoreCountFromLocal(bookcaseid);
                    if ((count + _pickerFiles.Count)>30)
                    {
                        var md = new MessageDialog("选择的书架容量不够（上限30本）！");
                        await md.ShowAsync();
                        return;
                    }

                    var errors = "";
                    var catchMsg = "";
                    foreach (var file in _pickerFiles)
                    {
                        if (await NReader.Service.ArticleService.Instance().ExistsArticle(file.Name.Replace(file.FileType, string.Empty)))
                        {
                            errors += string.Format("{0};", file.Name);
                            continue;
                        }
                        //本地数据库处理
                        var article = new ArticleInfo
                                          {
                                              articleid = maxid,
                                              articlename = file.Name.Replace(file.FileType,string.Empty),
                                              online = 0,
                                              articletype = file.FileType,
                                              historyprogress = 0,
                                              updatetime = DateTime.Now.ToString("yyyyMMddHHmmss")
                                          };
                        if (await NReader.Service.ArticleService.Instance().AddBook(article) == false)
                        {
                            catchMsg += string.Format("{0};", file.Name);
                            continue;
                        }
                        if (
                            await
                            NReader.Service.ArticleService.Instance().AddBookStoreToLocal(article.articleid, bookcaseid) ==
                            false)
                        {
                            catchMsg += string.Format("{0};", file.Name);
                            continue;
                        }
                        maxid++; //最大ID+1
                        //?san 判断文件是否存在未实现
                        //文件处理
                        file.CopyAsync(subfolder, file.Name, NameCollisionOption.ReplaceExisting);
                    }
                    if (!string.IsNullOrEmpty(errors))
                    {
                        errors += "\r\n文件已存在,请修改文件名后导入!";
                        if (!string.IsNullOrEmpty(catchMsg))
                        {
                            errors += catchMsg + "\r\n执行数据错误";
                        }
                        var md = new MessageDialog(errors);
                        await md.ShowAsync();
                    }
                    Frame.Navigate(typeof(Bookcase), bookcaseid);
                }

                #region 重新导入后，刷新章节页面缓存的数据

                ChapterIndex._article.articleid = 0;
                ChapterIndex._article.articlename = string.Empty;
                ChapterIndex._article.historyprogress = 0;
                ChapterIndex._article.historychapterid = 0;
                ChapterIndex._article.historychapter = "";
                ChapterIndex._posStart = 0;
                ChapterIndex._posEnd = 0;
                ChapterIndex._content = string.Empty;

                #endregion
                popBookcases.IsOpen = false;
                borderPopBookcases.Visibility = Visibility.Collapsed;
            }
        }

        private void CancelpopBookcasesClicked(object sender, RoutedEventArgs e)
        {
            if (popBookcases.IsOpen)
            {
                popBookcases.IsOpen = false;
                borderPopBookcases.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (navigationParameter != null)
            {
                var bookcaseId = navigationParameter.ToString();
                if (!string.IsNullOrEmpty(bookcaseId))
                {
                    _bookcaseId = int.Parse(bookcaseId);
                }
            }

            var list = await NReader.Service.GlobalService.Instance().GetBookCaseAndHistory(_bookcaseId);
            DefaultViewModel["Groups"] = list;

            var bookcases = await NReader.Service.GlobalService.Instance().GetBookCases();
            cvsBookcases.Source = bookcases;
            if (cmbBookcases.Items.Count > 0)
                cmbBookcases.SelectedIndex = 0;
        }

        private void ItemGridViewItemClick(object sender, ItemClickEventArgs e)
        {
            var item = e.ClickedItem as ArticleInfo;
            if (item != null)
            {
                ItemClick(item);
                //if (item.GroupName.Equals("nav"))
                //{
                //    //?san 后续修改为frame刷新书架内容
                //    Frame.Navigate(typeof (Bookcase), item.articleid);
                //}
                //else if (item.GroupName.Equals("最近阅读") || item.GroupName.Equals("我的书架"))
                //{
                //    //"跳转来源标记"+书籍ID+书名+上次阅读章节名称+上次阅读章节ID+阅读进度+是否在线 

                //    //?san 作废 "跳转来源标记"+书籍ID
                //    if (item.online.Equals(0)) //本地导入的书籍."跳转来源标记"+书籍ID+书名+文件后缀名+阅读进度+上一章/下一章/当前章节+章节ID
                //    {
                //        var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "offline",
                //                                  item.articleid,
                //                                  item.articlename,
                //                                  item.articletype,
                //                                  item.historyprogress,
                //                                  item.historychapterid.Equals(0)
                //                                      ? item.lastchapterid
                //                                      : item.historychapterid);
                //        Frame.Navigate(typeof (ChapterIndex), param);
                //    }
                //    else
                //    {
                //        var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "online",
                //                                  item.articleid,
                //                                  item.articlename,
                //                                  item.articletype,
                //                                  item.historyprogress,
                //                                  item.historychapterid.Equals(0)
                //                                      ? item.lastchapterid
                //                                      : item.historychapterid);//历史阅读章节ID为空时，显示最新章节ID
                //        if(!item.historychapterid.Equals(0))
                //        {
                //            Frame.Navigate(typeof(ChapterIndex), param);
                //        }
                //        else
                //        {
                //            Frame.Navigate(typeof (Book), item.articleid);//直接加入书架还未点击阅读的书跳转到book页面
                //        }
                //    }
                //}
            }
        }

        private void ItemListViewItemClick1(object sender, ItemClickEventArgs e)
        {
            var item = e.ClickedItem as ArticleInfo;
            if (item != null)
            {
                ItemClick(item);
            }
        }
    
        private void ItemClick(ArticleInfo item)
        {
            if (item.GroupName.Equals("nav"))
            {
                //?san 后续修改为frame刷新书架内容
                Frame.Navigate(typeof(Bookcase), item.articleid);
            }
            else if (item.GroupName.Equals("最近阅读") || item.GroupName.Equals("我的书架"))
            {
                //"跳转来源标记"+书籍ID+书名+上次阅读章节名称+上次阅读章节ID+阅读进度+是否在线 

                //?san 作废 "跳转来源标记"+书籍ID
                if (item.online.Equals(0)) //本地导入的书籍."跳转来源标记"+书籍ID+书名+文件后缀名+阅读进度+上一章/下一章/当前章节+章节ID
                {
                    var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "offline",
                                              item.articleid,
                                              item.articlename,
                                              item.articletype,
                                             (decimal)item.historyprogress,
                                              item.historychapterid.Equals(0)
                                                  ? item.lastchapterid
                                                  : item.historychapterid);
                    Frame.Navigate(typeof(ChapterIndex), param);
                }
                else
                {
                    var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "online",
                                              item.articleid,
                                              item.articlename,
                                              item.articletype,
                                             (decimal)item.historyprogress,
                                              item.historychapterid.Equals(0)
                                                  ? item.lastchapterid
                                                  : item.historychapterid);//历史阅读章节ID为空时，显示最新章节ID
                    if (!item.historychapterid.Equals(0))
                    {
                        Frame.Navigate(typeof(ChapterIndex), param);
                    }
                    else
                    {
                        Frame.Navigate(typeof(Book), item.articleid);//直接加入书架还未点击阅读的书跳转到book页面
                    }
                }
            }
        }
    }
}
